package com.jame.basics.io;

import org.junit.Test;

import java.io.*;

public class IoStudy {
    private String writerPath = "D:/words/daz.txt";
    private String readerPath = "D:/words/word1.txt";
    private File writerFilePath = new File(writerPath);


    /**
     * 通过FileWriter写入
     *
     * @throws IOException
     */
    @Test
    public void fileWriter() throws IOException {
        //FileWriter参数可以传入File,也可以直接传入String类型的绝对路径
        //第二个参数为是否追加,true为追加,false为覆盖
        FileWriter fileWriter = new FileWriter(writerFilePath, true);


        //一次写入一个char
        //fileWriter.append('g');

        //一次写入多个字符
        //fileWriter.write("啦啦啦");

        //只写入从下标0开始2位置长度为3的字符串(包含2)
        //fileWriter.write("1234567890",2,3);


        //写入char数组,从下标1开始,长度为1,写入数字2
        char[] chars = new char[10];
        chars[0] = '1';
        chars[1] = '2';
        chars[2] = '3';
        chars[3] = '4';
        fileWriter.write(chars, 1, 1);

        //FileWriter可以直接写入文件中,但是最好加上flush将缓冲区的数据写入文件中,以防万一
        fileWriter.flush();
        //关闭资源
        fileWriter.close();
    }

    /**
     * 通过BufferedWriter写入
     *
     * @throws IOException
     */
    @Test
    public void bufferedWriter() throws IOException {
        FileWriter fileWriter = new FileWriter(writerPath);
        BufferedWriter writer = new BufferedWriter(fileWriter);
        //覆盖
       // writer.write("123");
        //追加
        writer.append("qwe ");
        writer.flush();
        writer.close();

    }

    /**
     * 通过FileReader
     *
     * @throws IOException
     */
    @Test
    public void fileReader() throws IOException {
        FileReader reader = new FileReader(readerPath);
        char[] chars = new char[10];
        //写入char数组,从下标2开始写入,写入5个字符,如果长度大于定义的数组会报下标超出异常
        reader.read(chars, 2, 5);
        for (char aChar : chars) {
            System.out.println(aChar);
        }
        reader.close();

    }

    /**
     * 通过BufferedReader一行一行读取
     *
     * @throws IOException
     */
    @Test
    public void bufferedReader() throws IOException {
        FileReader fileReader = new FileReader(readerPath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        FileWriter fileWriter = new FileWriter(writerPath);
        BufferedWriter writer = new BufferedWriter(fileWriter);
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            String [] arr = line.split("\\s+");
            for(String ss : arr){
                for (int i = 0; i < 8; i++) {
                    if(i==7){
                        writer.append(ss+"\n");
                    }else {
                        writer.append(ss+" ");
                    }
                }

            }
        }
        bufferedReader.close();

    }


    @Test
    public void er() throws IOException {

    }

}
